#!/usr/bin/env sh

# Script to deploy certificates to conversant CDN

# The following variables exported from environment will be used.
# If not set then values previously saved in domain.conf file are used.
#
#
# export DEPLOY_CONVERSANT_CDN_ID=""  # access key id
# export DEPLOY_CONVERSANT_CDN_SECRET=""  # access key secret
# export DEPLOY_CONVERSANT_CDN_DOMAINS=""  # domains, used for SAN or wildcard certificate

########  Public functions #####################
conversant_cdn_deploy() {
  _cdomain="$1"
  _ckey="$2"
  _ccert="$3"
  _cca="$4"
  _cfullchain="$5"

  _debug _cdomain "$_cdomain"
  _debug _ckey "$_ckey"
  _debug _ccert "$_ccert"
  _debug _cca "$_cca"
  _debug _cfullchain "$_cfullchain"

  # access key id is required to access Conversant api. 
  _migratedeployconf Le_Deploy_conversant_cdn_id DEPLOY_CONVERSANT_CDN_ID
  _getdeployconf DEPLOY_CONVERSANT_CDN_ID
  _debug2 DEPLOY_CONVERSANT_CDN_ID "$DEPLOY_CONVERSANT_CDN_ID"
  if [ -z "$DEPLOY_CONVERSANT_CDN_ID" ]; then
    _err "DEPLOY_CONVERSANT_CDN_ID not defined."
    return 1
  fi
  _savedeployconf DEPLOY_CONVERSANT_CDN_ID "$DEPLOY_CONVERSANT_CDN_ID" 

  # access key secret is required to access Conversant api. 
  _migratedeployconf Le_Deploy_conversant_cdn_secret DEPLOY_CONVERSANT_CDN_SECRET
  _getdeployconf DEPLOY_CONVERSANT_CDN_SECRET
  _debug2 DEPLOY_CONVERSANT_CDN_SECRET "$DEPLOY_CONVERSANT_CDN_SECRET"
  if [ -z "$DEPLOY_CONVERSANT_CDN_SECRET" ]; then
    _err "DEPLOY_CONVERSANT_CDN_SECRET not defined."
    return 1
  fi
  _savedeployconf DEPLOY_CONVERSANT_CDN_SECRET "$DEPLOY_CONVERSANT_CDN_SECRET" 


  # domain names is required when deploy SAN or wildcard cert.
  _migratedeployconf Le_Deploy_conversant_cdn_domains DEPLOY_CONVERSANT_CDN_DOMAINS
  _getdeployconf DEPLOY_CONVERSANT_CDN_DOMAINS
  _debug2 DEPLOY_CONVERSANT_CDN_DOMAINS "$DEPLOY_CONVERSANT_CDN_DOMAINS"
  if [ -z "$DEPLOY_CONVERSANT_CDN_DOMAINS" ]; then
    DEPLOY_CONVERSANT_CDN_DOMAINS=$_cdomain
  fi
  _adomains=`echo $DEPLOY_CONVERSANT_CDN_DOMAINS` 
  _savedeployconf DEPLOY_CONVERSANT_CDN_DOMAINS "$DEPLOY_CONVERSANT_CDN_DOMAINS"
  
  _conversant_cdn_deploy

  _err_code="$?"
  return $_err_code
}

_conversant_cdn_deploy() {

  cmd="$DEFAULT_INSTALL_HOME/deploy/conversant_deploy.py"                  
  python3 $cmd -i $DEPLOY_CONVERSANT_CDN_ID -a $DEPLOY_CONVERSANT_CDN_SECRET \
  -d "$_adomains" -c "$_cfullchain" -k "$_ckey"

  _err_code="$?"
  return $_err_code

}



